package info.batcloud.fanli.background.task.scheduler;

import info.batcloud.fanli.core.entity.ItemSelection;
import info.batcloud.fanli.core.enums.ItemSelectionStatus;
import info.batcloud.fanli.core.repository.ItemSelectionRepository;
import info.batcloud.fanli.core.service.ItemSelectionService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class ItemSelectionScheduler {

    @Inject
    private ItemSelectionRepository itemSelectionRepository;

    @Inject
    private ItemSelectionService itemSelectionService;

    private ThreadPoolExecutor threadPoolExecutor;

    @PostConstruct
    public void init() {
        threadPoolExecutor = new ThreadPoolExecutor(5, 20, 5, TimeUnit.HOURS, new LinkedBlockingQueue<>());
    }

    @Scheduled(cron = "${cron.autoFetchItemSelection}")
    public void autoFetchItemSelection() {
        List<ItemSelection> list = itemSelectionRepository.findByStatusAndAutoFetch(ItemSelectionStatus.ACTIVE, true);

        for (ItemSelection itemSelection : list) {
            threadPoolExecutor.execute(() -> itemSelectionService.collectByItemSelectionId(itemSelection.getId()));
        }
    }

}
